/**
 * 分类管理列表组件
 */
import React, { Component } from "react";
import {
  Row,
  Col,
  Button,
  Modal,
  Spin,
  Table,
  Space,
  Typography,
  Input,
  Select,
  Form,
} from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { observer } from "mobx-react";
import { observable } from "mobx";
import moment from "moment";
import { WebVariable } from "../../../../../../data/WebVariable";
import IconFont from "../../../../../../assets/ICON";
import {
  getBaseDeviceType,
  deleteDeviceType,
  addDeviceType,
  updateDeviceType,
  getDeviceTypeByPage,
} from "../../../ServeApi";

import { AjaxData } from "../../../../../../data/interface/publicInterface";
const { Text } = Typography;
const { Option } = Select;
export interface SubItemTableProps {}

export interface SubItemTableState {
  loading: boolean;
}
interface columnsDataCLass {
  title: string;
  dataIndex: string;
  key: string;
  render?: any;
}
interface ISubItemFromDataClass {
  name: string;
  category: string;
  id?: string;
}
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
    md: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
    md: { span: 16 },
  },
};
@observer
class SubItemTable extends Component<SubItemTableProps, SubItemTableState> {
  @observable dataSouce: any[] = [];
  @observable
  private columns: columnsDataCLass[] = [
    {
      title: "分项类型",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "能源类型",
      dataIndex: "category",
      key: "category",
      render: (text: string) => {
        switch (text) {
          case "1":
            return <>电</>;
          case "2":
            return <>水</>;
          case "3":
            return <>煤</>;
          case "4":
            return <>油</>;
          case "5":
            return <>气</>;
          default:
            return <>暂无</>;
        }
      },
    },
    {
      title: "创建人",
      dataIndex: "createBy",
      key: "createBy",
      render: (text: string | null) => {
        if (text) {
          return text;
        } else {
          return "暂无";
        }
      },
    },
    {
      title: "创建时间",
      dataIndex: "createTime",
      key: "createTime",
      render: (text: string | null) => {
        if (text) {
          return moment(text).format("YYYY-MM-DD");
        } else {
          return "暂无";
        }
      },
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      render: (text, record) => {
        return (
          <>
            <Space size={26}>
              <span
                style={{ color: "#595959", cursor: "pointer" }}
                onClick={() => {
                  this.Mod = "updata";
                  this.onEdit(record);
                }}
              >
                <IconFont
                  type="icon_form_bianji"
                  style={{ color: "#FBB10B" }}
                />
                <Text>编辑</Text>
              </span>
              <span
                style={{ color: "#595959", cursor: "pointer" }}
                onClick={() => {
                  this.onDelete(record);
                }}
              >
                <IconFont
                  type="icon_form_shanchu"
                  style={{ color: "#FF6B6B" }}
                />
                <Text>删除</Text>
              </span>
            </Space>
          </>
        );
      },
    },
  ];
  state = { loading: false };
  private Mod: string = "add";
  private isModalVisible: boolean = false;
  private instance: any = null;
  private initValue: any = null;
  private pageIndex: number = 1;
  private pageSize: number = 20;
  private total: number = 0;
  render() {
    return (
      <>
        <div className="SubItemTable">
          <div className="rowcon_body">
            <div>
              <Button
                type="primary"
                icon={<PlusOutlined />}
                onClick={() => {
                  this.Mod = "add";
                  this.addMenuModal();
                }}
              >
                新增
              </Button>
            </div>
            <div className="rowcon_bottom"></div>
            <Spin spinning={this.state.loading}>
              <Table
                columns={this.columns}
                dataSource={this.dataSouce}
                pagination={{
                  pageSize: this.pageSize,
                  current: this.pageIndex,
                  total: this.total,
                  onChange: (page: number) => {
                    this.pageIndex = page;
                    this.getPream();
                  },
                }}
              ></Table>
            </Spin>
            <Modal
              title={this.Mod === "add" ? "新增分项" : "编辑分项"}
              visible={this.isModalVisible}
              onOk={() => {
                this.handleOk();
              }}
              onCancel={() => {
                this.handleCancel();
              }}
            >
              <Form {...formItemLayout} ref={(el) => (this.instance = el)}>
                <Row>
                  <Col span={24}>
                    <Form.Item
                      label="分项类型："
                      name="name"
                      rules={[
                        {
                          required: true,
                          message: "分项类型必填",
                        },
                      ]}
                    >
                      <Input placeholder="请填写分项类型" />
                    </Form.Item>
                  </Col>
                  <Col span={24}>
                    <Form.Item
                      label="能源类型："
                      name="category"
                      rules={[
                        {
                          required: true,
                          message: "能源类型必填",
                        },
                      ]}
                    >
                      <Select placeholder="请选择能源类型">
                        {WebVariable.categoryType.map((item: any) => {
                          return (
                            <Option value={item.key} key={item.key}>
                              {item.label}
                            </Option>
                          );
                        })}
                      </Select>
                    </Form.Item>
                  </Col>
                </Row>
              </Form>
            </Modal>
          </div>
        </div>
      </>
    );
  }
  componentWillMount() {
    this.getListByPage();
  }

  /**被动操作 */
  //
  getPream() {}
  ifVisible() {
    this.isModalVisible = !this.isModalVisible;
    this.forceUpdate();
  }
  //参数处理与新增，编辑函数的参数
  setPream(item: ISubItemFromDataClass) {
    switch (this.Mod) {
      case "add":
        this.AddSubItem(item);
        break;
      case "updata":
        item["id"] = this.initValue["id"];
        this.EditSubItem(item);
        break;
      default:
        break;
    }
  }
  //清空From表单
  clearFromData() {
    this.initValue = null;
    if (this.instance) {
      const container: any = (this.instance as any) as HTMLDivElement;
      container.setFieldsValue({
        name: undefined,
        category: undefined,
      });
    }
  }
  //弹窗取消
  handleCancel() {
    this.ifVisible();
    this.clearFromData();
  }
  //弹窗确认
  handleOk() {
    let _this = this;
    const container: any = (this.instance as any) as HTMLDivElement;
    container
      .validateFields()
      .then((res) => {
        _this.setPream(res);
        _this.ifVisible();
        _this.clearFromData();
      })
      .catch((err) => {
        console.log(err);
      });
  }
  /**主动操作 */
  //新增菜单对话框
  addMenuModal() {
    this.ifVisible();
  }
  //编辑用户
  onEdit(item) {
    this.initValue = item;
    this.ifVisible();
    setTimeout(() => {
      if (this.instance) {
        const container: any = (this.instance as any) as HTMLDivElement;
        container.setFieldsValue(item);
      }
    });
  }
  //删除用户
  onDelete(item) {
    let pream = {
      id: item.id,
    };
    let _this = this;
    Modal.confirm({
      title: "是否确认删除用户",
      onOk: () => {
        _this.DeleteSubItem(pream);
      },
    });
  }
  /**请求数据 */
  //获取分项列表
  private async getList() {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await getBaseDeviceType({}).catch((err) => {
        console.log(err);
        _this.setState({ loading: false });
      });
      let json = res;
      if (json.success) {
        this.dataSouce = json.data;
        this.setState({ loading: false });
        this.forceUpdate();
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //新增分项
  private async AddSubItem(item: ISubItemFromDataClass) {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await addDeviceType(JSON.stringify(item)).catch((err) => {
        console.log(err);
        _this.setState({ loading: false });
      });
      let json: AjaxData = res;
      if (json.success) {
        _this.getListByPage();
        _this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  //编辑分项
  private async EditSubItem(item: ISubItemFromDataClass) {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await updateDeviceType(JSON.stringify(item)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.getListByPage();
        _this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  private async DeleteSubItem(pream: { id: string }) {
    let _this = this;
    this.setState({ loading: true });
    try {
      let res: any = await deleteDeviceType(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.getListByPage();
        _this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
  private async getListByPage() {
    let _this = this;
    this.setState({ loading: true });
    let pream = {
      pageIndex: this.pageIndex,
      pageSize: this.pageSize,
      queryData: null,
    };
    try {
      let res: any = await getDeviceTypeByPage(JSON.stringify(pream)).catch(
        (err) => {
          console.log(err);
          _this.setState({ loading: false });
        }
      );
      let json: AjaxData = res;
      if (json.success) {
        _this.dataSouce = json.data.records;
        _this.total = json.data.total;
        _this.setState({ loading: false });
      } else {
        Modal.error({
          title: json.message,
          onOk: () => {
            _this.setState({ loading: false });
          },
        });
      }
    } catch (error) {
      Modal.error({
        title: "初始化程序失败，无法读取数据，请刷新页面。",
        onOk: () => {
          _this.setState({ loading: false });
        },
      });
      console.error(error);
    }
  }
}

export default SubItemTable;
